<?php

namespace common\models\inventory;

use Yii;
use yii\helpers\Inflector;

/**
 * This is the model class for table "{{%bill}}".
 *
 * @property int $id
 * @property string $bill_no 票据编号
 * @property int $type_id 类型ID
 * @property int $company_id 公司单位ID
 * @property int $user_id 用户ID
 * @property int $nums 标签数
 * @property string $token 校验令牌
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class InventoryBill extends \common\models\bill\Bill {

    const TYPE_SURPLUS = 'surplus';
    const TYPE_LOSS = 'loss';
    const TYPE_NORMAL = 'normal';
    const TYPE_DEFAULT = '';

    public $batch = null;
    public $type = '';

    public function search() {
        $method = 'query' . Inflector::camelize($this->type);
        $handler = array($this, $method);
        $query = $this->findActive('t', static::STATUS_ACTIVE);
        if ($this->hasMethod($method) && is_callable($handler)) {
            $query = call_user_func_array($handler, [$query]);
            $expression = new \yii\db\Expression("'" . $this->type . "' as type");
            $query->addSelect(['t.*', $expression]);
            return $query->all();
        }
        return [];
    }

    private function querySurplus($query) {
        $query->joinWith([
            'logs' => function ($q) {
                $q->alias('logs')->andWhere([
                    'and',
                    ['logs.batch_id' => $this->batch->id],
                    ['>', 'logs.status', InventoryLog::STATUS_DEFAULT],
                ])
                ->groupBy('logs.bill_id')
                ->having('count(*)>1');
            }
        ], false);
        return $query;
    }

    /**
     * sql:
     * SELECT `t`.* FROM `yb_bill` `t` LEFT JOIN `yb_inventory_log` `logs` ON `t`.`id` = `logs`.`bill_id`
     * WHERE (`t`.`deleted_at`=0) AND (`t`.`status`=10) AND (`t`.`type_id`=1) AND
     * ((`logs`.`id` IS NULL) OR ((`logs`.`bill_id` IS NULL) AND (`logs`.`batch_id`=23) AND (`logs`.`status` > 0)))
     * sql
     * @param type $query
     * @return type
     */
    private function queryLoss($query) {
        $query->joinWith('logs logs')
        ->andWhere(['t.type_id' => $this->batch->type_id])
        ->andWhere([
            'or',
            ['logs.id' => null],
            [
                'and',
                ['logs.bill_id' => null],
                ['logs.batch_id' => $this->batch->id],
                ['>', 'logs.status', InventoryLog::STATUS_DEFAULT],
            ]
        ]);
        return $query;
    }

    private function queryNormal($query) {
        $query->joinWith([
            'logs' => function ($q) {
                $q->alias('logs')->andWhere([
                    'and',
                    ['logs.batch_id' => $this->batch->id],
                    ['>', 'logs.status', InventoryLog::STATUS_DEFAULT],
                ])
                ->groupBy('logs.bill_id')
                ->having('count(*)=1');
            }
        ], false);
        return $query;
    }

    public function getMessage() {
        $messages = [
            static::TYPE_LOSS => '缺失票据',
            static::TYPE_NORMAL => '正常',
            static::TYPE_SURPLUS => '多余票据',
        ];
        return \common\helpers\ArrayHelper::getValue($messages, $this->type);
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'bill_no',
            'type',
            'route',
            'message'
        ];
    }

}
